package com.thunder.rebot.rebotclient.activity;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.esotericsoftware.kryonet.Client;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.limedia.explorer.centralcontrol.ControlActivity;
import com.limedia.explorer.utils.CommonUtils;
import com.thunder.rebot.rebotclient.R;
import com.thunder.rebot.rebotclient.application.RobotApplication;
import com.thunder.rebot.rebotclient.constant.Constants;
import com.thunder.rebot.rebotclient.entity.SocketConectState;
import com.thunder.rebot.rebotclient.entity.TaskDots;
import com.thunder.rebot.rebotclient.entity.UserInformationEntity;
import com.thunder.rebot.rebotclient.service.ServiceClient;
import com.thunder.rebot.rebotclient.utils.ClientUtils;
import com.thunder.rebot.rebotclient.utils.DialogUtils;
import com.thunder.rebot.rebotclient.view.CustomDialog;
import com.ts.robot.socket.TSRobotSocketNative;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yuechunan on 18-7-17.
 */

public class WelcomeActivity  extends BaseActivity {

    private static final String TAG = WelcomeActivity.class.getSimpleName();
    @BindView(R.id.edt_ip)
    public EditText edtIp;
    @BindView(R.id.btn_ok)
    public Button btnOK;
    @BindView(R.id.rl_back)
    public RelativeLayout rlBack;

    @BindView(R.id.center_txt)
    public TextView centerTxt;


    @BindView(R.id.right_txt)
    public TextView rightTxt;

    @BindView(R.id.edt_ip_robot)
    public EditText edtIpRobot;
    @BindView(R.id.btn_ok_robot)
    public Button btnOkRobot;
    @BindView(R.id.btn_test)
    public Button btnTest;


    private Client client;
    private SharedPreferences sharedPreferences;



    public static String title = "TS Robot Client";
    private  TSRobotSocketNative tsRobotSocketNative;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        ButterKnife.bind(this);
        sharedPreferences = getSharedPreferences("ip", MODE_PRIVATE);
//        if(ClientUtils.connectFlag){
//            Intent intent = new Intent(this, MainActivity.class);
//            startActivity(intent);
//        }
        centerTxt.setText(title);
        rightTxt.setText(R.string.regist_face);
        rightTxt.setVisibility(View.VISIBLE);
        initRobotSocket();
        showAlertDialog(this);
//        if(RobotApplication.TEST){
//            Intent intent=new Intent(this,ServiceClient.class);
//            startService(intent);
//        }
    }



    public void showAlertDialog(final Context context) {
//        View view = LayoutInflater.from(context).inflate(R.layout.item_alertdialog_layout, null);// 自定义布局
//        final CustomDialog dialog = new CustomDialog(context, R.layout.item_alertdialog_layout, 0);
//        Button btnQuXiao = (Button) view.findViewById(R.id.btn_alertdialog_quxiao);
//        final EditText taskFrom = (EditText) view.findViewById(R.id.et_alertdialog_task1);
//        final EditText taskTo = (EditText) view.findViewById(R.id.et_alertdialog_task2);
////        etCompany.setFocusable(false);//设置第一个edittext不可手动输入内容(即不可获取焦点),必须从右侧的下拉列表中选取 //配置下拉列表
        Spinner spfrom = (Spinner) findViewById(R.id.iv_alertdialog_location1);
//        Spinner spto = (Spinner) findViewById(R.id.iv_alertdialog_location2);

        ArrayAdapter<CharSequence> adapterfrom = ArrayAdapter.createFromResource(context, R.array.locations, android.R.layout.simple_spinner_item);
        adapterfrom.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spfrom.setAdapter(adapterfrom);  //为下拉列表设置监听
        spfrom.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                String company = context.getResources().getStringArray(R.array.locations)[arg2];//获取选择的item内容
//                taskFrom.setText(company);//将下拉列表中选择的item内容填充到前面的edittext中
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub
            }
        });

//        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, R.array.locations, android.R.layout.simple_spinner_item);
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        spto.setAdapter(adapter);  //为下拉列表设置监听
//        spto.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//                String company = context.getResources().getStringArray(R.array.locations)[arg2];//获取选择的item内容
//                taskTo.setText(company);//将下拉列表中选择的item内容填充到前面的edittext中
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub
//            }
//        });

//        dialog.create();
//        dialog.show();

    }


    /**
     * 初始化robot socket
     */
    private  void initRobotSocket() {
        if(tsRobotSocketNative == null) {
            tsRobotSocketNative = new TSRobotSocketNative(this);
//            tsRobotSocketNative = TSRobotSocketNative.getTsRobotSocketNativeInstance();
            LoginActivity.setRobotSocket(tsRobotSocketNative);
            ControlActivity.setRobotSocket(tsRobotSocketNative);
            TaskActivity.setRobotSocket(tsRobotSocketNative);
            tsRobotSocketNative.addSocketLisetnerInterface(this);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        String firstIpvalue = sharedPreferences.getString("FirstIpAddress", "1");
        String robotIpAddress = sharedPreferences.getString("RobotIpAddress", "1");
        Log.e(TAG, "onResume:Address1"+firstIpvalue + "RobotIpAddress:" + robotIpAddress);
        edtIp.setText(firstIpvalue);
        edtIpRobot.setText(robotIpAddress);
        if("1".equals(edtIp.getText().toString())){
            edtIp.setText("192.168.1.1");
        }
        if("1".equals(edtIpRobot.getText().toString())){
            edtIpRobot.setText("192.168.1.2");
        }
    }

    @OnClick({R.id.btn_ok,R.id.rl_back,R.id.btn_ok_robot,R.id.btn_test,R.id.right_txt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_ok:
                String ip=edtIp.getText().toString().trim();
                boolean isFirstIpValid = CommonUtils.isIpAddressValid(ip);

                if(isFirstIpValid ){
                    //都是可用的ip
                    //保存ip trsp
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("FirstIpAddress", ip);
                    editor.commit();
                    //socket
                    Intent intent=new Intent(this,ServiceClient.class);
                    startService(intent);
                }else{
                    Toast.makeText(getApplicationContext(), "您输入的ip格式不正确，请重新输入",Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.btn_ok_robot:
                final String robotIp=edtIpRobot.getText().toString().trim();
                boolean isFirstIpValidRobot = CommonUtils.isIpAddressValid(robotIp);
                if(isFirstIpValidRobot){
                    SharedPreferences.Editor editor1 = sharedPreferences.edit();
                    editor1.putString("RobotIpAddress", robotIp);
                    editor1.commit();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            tsRobotSocketNative.init(robotIp);
                        }
                    }).start();
                }else{
                    Toast.makeText(getApplicationContext(), "您输入的ip格式不正确，请重新输入",Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.btn_test:
                DialogUtils.showAlertDialog(WelcomeActivity.this);
                break;
            case R.id.right_txt:
//                if(LogInUtils.passwdIsValid(etUser.getText().toString().trim(), etPasswd.getText().toString().trim(), Constants.userpwdMap)){
//                    //注册人脸
                  if(ClientUtils.robotConnectFlag && ClientUtils.connectFlag){
                      //判断是否连接
                    Intent intent = new Intent(WelcomeActivity.this,RegisterActivity.class);
//                    UserInformationEntity uife = new UserInformationEntity();
//                    uife.setName(etUser.getText().toString().trim());
//                    uife.setPasswd(etPasswd.getText().toString().trim());
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("uerinfo",uife);
//                    intent.putExtras(bundle);
                    startActivityForResult(intent, Constants.REQUESTCODE);
                }else{
                      runOnUiThread(new Runnable() {
                          @Override
                          public void run() {
                              Toast.makeText(WelcomeActivity.this, "连接服务器失败",Toast.LENGTH_SHORT).show();
                          }
                      });
                  }
                break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case Constants.REQUESTCODE:
                if (resultCode == Constants.RESPONSECODE){
                    // 注册人脸返回的结果
                    Toast.makeText(getApplicationContext(), "收到注册人脸返回的结果", Toast.LENGTH_SHORT).show();
                    //正式登录
                }

                break;
//            case REQUEST_ENABLE_BT:
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        tsRobotSocketNative.quit_native(false);
        tsRobotSocketNative.removeSocketLisetnerInterface(this);
//        tsRobotSocketNative =null;//release
    }

    @Override
    public void conectState(int code,final String description) {
        switch (code){
            case 1:
                Gson gson = new Gson();
               final SocketConectState socketConectState = gson.fromJson(description, new TypeToken<SocketConectState>() {}.getType());

                switch (Integer.valueOf(socketConectState.getCode())){
                    case 10://连接成功
                            ClientUtils.robotConnectFlag = true;




//                        startActivity(new Intent(WelcomeActivity.this, ControlActivity.class));//12.10
                        break;
                    case 9://连接断开
                        ClientUtils.robotConnectFlag = false;

                        break;
                    case 8://未连接成功
                        ClientUtils.robotConnectFlag = false;
                        break;
                }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(WelcomeActivity.this, socketConectState.getDescription(),Toast.LENGTH_SHORT).show();
            }
        });

                break;
        }
    }
}
